#include "../tools.h"

class Codec {
public:
    void sehelper(TreeNode* tree, string& str){
        if (tree == NULL){
            str += "None,";
            return;
        }

        str += to_string(tree->val) + ",";
        sehelper(tree->left, str);
        sehelper(tree->right, str);
    }
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string str;
        sehelper(root, str);
        return str;
    }

    TreeNode* desehelper(list<string>& val_list){
        if (val_list.front() == "None"){
            val_list.erase(val_list.begin());
            return nullptr;
        }

        TreeNode* root = new TreeNode(stoi(val_list.front()));
        val_list.erase(val_list.begin());
        
        root->left  = desehelper(val_list);
        root->right = desehelper(val_list);
        return root;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        list<string> vals;
        string str;
        for(auto& ch: data){
            if (ch == ','){
                vals.push_back(str);
                str.clear();
            }else{
                str.push_back(ch);
            }
        }
        
        return desehelper(vals);
    }
};




int main(int argc, char const *argv[])
{
    Codec codec;

    int arr[7] = {3,9,20,-1,-1,15,7};
    TreeNode* p = create_tree(arr, 7);

    show(p);

    string t = codec.serialize(p);
    cout << t << endl;

    TreeNode* res = codec.deserialize(t);
    show(res);
    
    return 0;
}
